#include "hd_oled.h"
#include "delay.h"
#include "main.h"
#include "hd_mpu6050.h"


void SystemClock_Config(void);

int main(void) {
    LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SYSCFG);

    NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_2);

    SystemClock_Config();

    // OLED 初始化
    HD_OLED_Init(OLED_SIZE_16, OLED_MODE_POSITIVE);
    HD_OLED_Clear();

    HD_MPU6050_Init();
    HD_OLED_ShowString(0, 0, "ID:");
    HD_OLED_ShowHexNum(24, 0, HD_MPU6050_GetID(), 2);

    HD_MPU6050_DataTypeDef MPU6050_DataStruct;

    while (1) {
        HD_MPU6050_GetData(&MPU6050_DataStruct);
        HD_OLED_ShowSignedNum(0, 16, MPU6050_DataStruct.accX, 5);
        HD_OLED_ShowSignedNum(0, 32, MPU6050_DataStruct.accY, 5);
        HD_OLED_ShowSignedNum(0, 48, MPU6050_DataStruct.accZ, 5);
        HD_OLED_ShowSignedNum(64, 16, MPU6050_DataStruct.gyroX, 5);
        HD_OLED_ShowSignedNum(64, 32, MPU6050_DataStruct.gyroY, 5);
        HD_OLED_ShowSignedNum(64, 48, MPU6050_DataStruct.gyroZ, 5);
    }

}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void) {
    LL_FLASH_SetLatency(LL_FLASH_LATENCY_4);
    while (LL_FLASH_GetLatency() != LL_FLASH_LATENCY_4) {
    }
    LL_PWR_EnableRange1BoostMode();
    LL_RCC_HSE_Enable();
    /* Wait till HSE is ready */
    while (LL_RCC_HSE_IsReady() != 1) {
    }

    LL_RCC_PLL_ConfigDomain_SYS(LL_RCC_PLLSOURCE_HSE, LL_RCC_PLLM_DIV_6, 85, LL_RCC_PLLR_DIV_2);
    LL_RCC_PLL_EnableDomain_SYS();
    LL_RCC_PLL_Enable();
    /* Wait till PLL is ready */
    while (LL_RCC_PLL_IsReady() != 1) {
    }

    LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_PLL);
    LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_2);
    /* Wait till System clock is ready */
    while (LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_PLL) {
    }

    /* Insure 1?s transition state at intermediate medium speed clock based on DWT */
    CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
    DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
    DWT->CYCCNT = 0;
    while (DWT->CYCCNT < 100);
    /* Set AHB prescaler*/
    LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);
    LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
    LL_RCC_SetAPB2Prescaler(LL_RCC_APB2_DIV_1);

    LL_Init1msTick(170000000);

    LL_SetSystemCoreClock(170000000);
}


#ifdef  USE_FULL_ASSERT

/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line) {
    /* USER CODE BEGIN 6 */
    /* User can add his own implementation to report the file name and line number,
       ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END 6 */
}

#endif /* USE_FULL_ASSERT */